package com.gxa.jjty.cjr.service.impl;

import com.gxa.jjty.cjr.mapper.CjrMapper;
import com.gxa.jjty.cjr.service.CjrUserService;
import com.gxa.jjty.cjr.utils.MessageUtil;
import com.gxa.jjty.core.common.ExceptionCode;
import com.gxa.jjty.core.common.JsonResult;
import com.gxa.jjty.core.exception.BusinessException;
import com.gxa.jjty.core.pojo.CjrUser;
import com.gxa.jjty.core.pojo.Complaint;
import com.gxa.jjty.core.pojo.Kinship;
import com.gxa.jjty.core.service.impl.BaseServiceImpl;
import com.gxa.jjty.core.util.JsonUtil;
import com.gxa.jjty.core.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @author NITRO
 */
@Service("cjrUserService")
public class CjrUserServiceImpl extends BaseServiceImpl<CjrUser> implements CjrUserService {


    @Autowired
    private MessageUtil messageUtil;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private CjrMapper cjrMapper;

    /**
     * 在spring和springboot中可直接对request实现注入/装配
     */
    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 设置token前缀
     */
    public static final String SECLRET = "TanFu+ShengS!haiDeYiPi";

    @Override
    public Map<String, String> login(String phone, String code) throws BusinessException {



        String redisCode = redisTemplate.opsForValue().get(SmsServiceImpl.LOGIN_SMS + phone).toString();
        redisTemplate.delete(SmsServiceImpl.LOGIN_SMS + phone);
        if (StringUtil.isEmpty(redisCode)) {
            throw new BusinessException(ExceptionCode.NOT_NULL);
        }
        if (!code.equals(redisCode)) {
            throw new BusinessException(ExceptionCode.CAPTCHA_FALSE);
        }
        Example example = new Example(CjrUser.class);
        example.createCriteria().andEqualTo("phone",phone);
        List<CjrUser> cjrUsers = cjrMapper.selectByExample(example);
        CjrUser findUser = cjrUsers.get(0);
        if (findUser == null) {
            findUser=new CjrUser();
            findUser.setPhone(phone);
            findUser.setRegTime(new Date());
            findUser.setName("用户"+phone);
            cjrMapper.insert(findUser);
        }else {
            findUser.setAddress(httpServletRequest.getRemoteAddr());
            findUser.setRegTime(new Date());
            cjrMapper.updateByPrimaryKey(findUser);
        }

        String token1 = findUser.getToken();
        redisTemplate.delete(SECLRET+token1);

        String token = UUID.randomUUID().toString().replace("-", "");
        findUser.setToken(token);
        String userJsonString = JsonUtil.objectToString(findUser);

        redisTemplate.opsForValue().set(SECLRET+token,userJsonString,2, TimeUnit.HOURS);

        Map<String, String> result = new HashMap<>();
        result.put("token", token);

        return result;
    }

    @Override
    public CjrUser queryUserByToken(String token) {
        return  null;
    }

    @Override
    public void logout(String phone ) {
        redisTemplate.delete(SmsServiceImpl.LOGIN_SMS + phone);
    }

    @Override
    public CjrUser selectUser(String phone) throws BusinessException {

        Example example = new Example(CjrUser.class);
        example.createCriteria().andEqualTo("phone",phone);
        List<CjrUser> cjrUsers = cjrMapper.selectByExample(example);
        if (cjrUsers.size()<0) {
            throw new BusinessException(ExceptionCode.NO_CUSTOMER);
        }
        return cjrUsers.get(0);
    }

    @Override
    public void updateUser(CjrUser user) {
        cjrMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Map<String, Object> selectById(Long id) throws BusinessException {
        Object o = redisTemplate.opsForValue().get("cjrUser:" + id);
        HashMap<String, Object> map = new HashMap<>(16);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(o);
        if (o==null){
            CjrUser cjrUser = cjrMapper.selectByPrimaryKey(id);
            if (cjrUser==null){
                throw new BusinessException(ExceptionCode.NODATA);
            }
            List<Kinship> kinships = cjrMapper.selectKinShip(id);
            map.put("cjrUser",cjrUser);
            map.put("kinship",kinships);
            jsonResult.setData(map);
            redisTemplate.opsForValue().set("cjrUser:" + id,map);
        }

        return jsonResult.getDataMap();
    }

    @Override
    public Map<String, Object> feedback(Long id,String content) throws BusinessException {
        HashMap<String, Object> map = (HashMap<String, Object>)redisTemplate.opsForValue().get("cjrUser:" + id);
        CjrUser cjrUser=null;
        if (map==null){
            cjrUser = cjrMapper.selectByPrimaryKey(id);
        }else {
            cjrUser = JsonUtil.stringToObject(JsonUtil.objectToString(map.get("cjrUser")), CjrUser.class);
        }
        final Complaint complaint = new Complaint();
        complaint.setName(cjrUser.getName());
        complaint.setHandicappedId(cjrUser.getId());
        complaint.setCreatedTime(new Timestamp(System.currentTimeMillis()));
        complaint.setPhone(cjrUser.getPhone());
        complaint.setContent(content);

        int feedback = cjrMapper.feedback(complaint);
        if (feedback!=1){
            throw new BusinessException(ExceptionCode.FEEDBACK_FALSE);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("反馈成功!");
        return jsonResult.getDataMap();
    }

    @Override
    public Map<String, Object> messageInform(Long id) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(messageUtil.getMsg(id));
        return jsonResult.getDataMap();
    }


}
